<script setup>
import { ref, watch, onMounted, watchEffect } from 'vue'
import { nextTick } from 'vue'
import { useExperimentStore } from '@/stores/experimentStore'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import { useTokenStore } from '@/stores/tokens'
import api from '@/api/request' // 导入封装的 api 实例

import { ElLoading } from 'element-plus'
import 'element-plus/dist/index.css'

import CommonHeader from '@/views/common/CommonHeader.vue'

const addGroupDialogVisible = ref(false)
const editGroupForm = ref(null)
const newGroupName = ref('')

const router = useRouter()
// 使用 ref 来存储输入框的值
const teamNameStore = useExperimentStore()
const nameGroup = ref({ teamName: '', exper_name: '' })

const radios = ref(2) // 默认选中变化趋势
const isFolderUploaded = ref(true)
// 对话框及当前编辑项状态

const currentRoundIndex = ref(null)
const currentTimePointIndex = ref(null)

const directoryInputRefs = ref({})
// 定义实验列表
//新建实验对话框
const dialogNewExp = ref(false)
const newExperimentData = ref({
  experimentName: '',
  teamName: ''
})

const experimentDetectList = ref([
  {
    experimentName: '321',
    experimentRounds: [
      {
        roundName: '第1次实验',
        isSelected: false, // 轮次是否被选中
        timePoints: [
          {
            timePointName: '',
            groups: [
              { groupname: '正常组', fileUrls: '', isSelected: false },
              { groupname: '感染组', fileUrls: '', isSelected: false },
              { groupname: '疫苗组', fileUrls: '', isSelected: false }
            ]
          }
        ]
      }
    ]
  }
])

const activeNames = ref([]) // 控制折叠面板的状态
const editGroupDialogVisible = ref(false)

const dialogFormVisible = ref(false)
const currentGroup = ref({ name: '' })
const currentGroupIndex = ref(null)

const currentExperimentIndex = ref(null) // 当前的实验索引
const formLabelWidth = '80px'
const errorMessage = ref('') // 存储错误信息

// 禁用超过当前的日期和时间，
const timePoint = ref({
  timePointName: null
})

// 禁用未来日期
const disabledDate = (date) => {
  const now = new Date()
  return date > now
}

// 禁用未来的小时
const disabledHours = () => {
  const now = new Date()
  const currentHour = now.getHours()

  if (isToday(timePoint.value.timePointName)) {
    // 如果选择的是今天，禁用当前小时之后的小时
    return Array.from({ length: 24 }, (_, i) => i).slice(currentHour + 1)
  }
  return []
}

// 禁用未来的分钟
const disabledMinutes = (selectedHour) => {
  const now = new Date()
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()

  if (isToday(timePoint.value.timePointName) && selectedHour === currentHour) {
    // 如果选择的是当前小时，禁用当前分钟之后的分钟
    return Array.from({ length: 60 }, (_, i) => i).slice(currentMinute + 1)
  }
  return []
}

// 禁用未来的秒
const disabledSeconds = (selectedHour, selectedMinute) => {
  const now = new Date()
  const currentHour = now.getHours()
  const currentMinute = now.getMinutes()
  const currentSecond = now.getSeconds()

  if (
    isToday(timePoint.value.timePointName) &&
    selectedHour === currentHour &&
    selectedMinute === currentMinute
  ) {
    // 如果选择的是当前小时和分钟，禁用当前秒之后的秒
    return Array.from({ length: 60 }, (_, i) => i).slice(currentSecond + 1)
  }
  return []
}

// 检查所选日期是否为今天
const isToday = (date) => {
  if (!date) return false
  const today = new Date()
  return (
    date.getFullYear() === today.getFullYear() &&
    date.getMonth() === today.getMonth() &&
    date.getDate() === today.getDate()
  )
}

// 修改 token 获取方式
const tokenStore = useTokenStore()
const setDirectoryInputRef = (
  el,
  experimentIndex,
  roundIndex,
  timePointIndex,
  groupIndex
) => {
  const refKey = `${experimentIndex}-${roundIndex}-${timePointIndex}-${groupIndex}`
  directoryInputRefs.value[refKey] = el
}

const triggerDirectoryInput = (
  experimentIndex,
  roundIndex,
  timePointIndex,
  groupIndex
) => {
  const refKey = `${experimentIndex}-${roundIndex}-${timePointIndex}-${groupIndex}`
  const inputRef = directoryInputRefs.value[refKey]

  if (inputRef) {
    inputRef.click()
  } else {
    ElMessage.error('未找到文件夹选择输入，请检查引用是否正确')
  }
}
const handleDirectoryChange = async (
  event,
  group,
  experimentIndex,
  roundIndex,
  timePointIndex
) => {
  const files = Array.from(event.target.files)

  // 调试信息：输出选择的文件数量和文件名
  console.log('选择的文件数量:', files.length)
  files.forEach((file) => console.log('文件名:', file.name))

  // 检查图片尺寸
  const validateImageDimensions = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (event) => {
        const img = new Image()
        img.onload = () => {
          console.log(`文件 ${file.name} 尺寸: ${img.width}x${img.height}`) // 调试信息
          if (img.width > 640 || img.height > 640) {
            reject(
              new Error(
                `文件 ${file.name} 的尺寸超出限制 (${img.width}x${img.height})`
              )
            )
          } else {
            resolve()
          }
        }
        img.onerror = () => reject(new Error(`无法读取文件 ${file.name}`))
        img.src = event.target.result
      }
      reader.onerror = () => reject(new Error(`无法加载文件 ${file.name}`))
      reader.readAsDataURL(file)
    })
  }

  try {
    // 检查所有文件的尺寸
    await Promise.all(
      files
        .filter((file) => file.type.startsWith('image/'))
        .map(validateImageDimensions)
    )

    if (files.length > 0) {
      const folderName =
        files[0].webkitRelativePath?.split('/')[0] || files[0].name

      // 为预览创建本地 URL
      group.previewUrls = files
        .filter((file) => file.type.startsWith('image/'))
        .map((file) => URL.createObjectURL(file))

      group.originalFiles = files // 保存原始文件用于上传
      console.log('原始文件:', group.originalFiles) // 调试信息
      group._displayFolderName = folderName
      await uploadFolders(group, experimentIndex, roundIndex, timePointIndex)
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(`文件上传失败，请重试: ${error.message}`)
    group.fileUrls = ''
    group._displayFolderName = ''
    // 清除预览 URL
    if (group.previewUrls) {
      group.previewUrls.forEach((url) => URL.revokeObjectURL(url))
      group.previewUrls = []
    }
  }
}

const uploadFolders = async (
  group,
  experimentIndex,
  roundIndex,
  timePointIndex
) => {
  let loadingInstance // 定义加载实例
  try {
    // 显示加载动画
    loadingInstance = ElLoading.service({
      lock: true,
      text: '文件上传中，请稍候...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    const formData = new FormData()
    const experiment = experimentDetectList.value[experimentIndex]
    const timePoint =
      experiment.experimentRounds[roundIndex].timePoints[timePointIndex]

    if (
      !Array.isArray(group.originalFiles) ||
      group.originalFiles.length === 0
    ) {
      throw new Error('没有可上传的文件')
    }

    // 检查文件是否为 .tif 格式，若是则报错并取消上传
    const invalidFiles = group.originalFiles.filter((file) => {
      const fileExtension = file.name.toLowerCase().split('.').pop()
      return fileExtension === 'tif' || file.type === 'image/tiff'
    })

    if (invalidFiles.length > 0) {
      // 提示用户不允许上传 tif 格式的图片
      ElMessage.error('不允许上传 TIFF (.tif) 格式的图片，请选择其他格式的图片')
      return // 取消上传
    }

    // 如果没有找到 tif 格式的文件，则继续上传
    formData.append(
      'roundName',
      experiment.experimentRounds[roundIndex].roundName
    )
    formData.append('timePointName', timePoint.timePointName)
    formData.append('groupName', group.name)

    // 调试：打印文件内容
    group.originalFiles.forEach((file) => {
      console.log('准备上传文件:', file)
      formData.append('multipartFiles', file) // 确保每个文件都被正确添加
    })

    // 调试：查看 FormData 内容
    for (let [key, value] of formData.entries()) {
      console.log(key, value)
    }

    const experimentName =
      nameGroup.value.exper_name || experiment.experimentName
    if (!experimentName) {
      throw new Error('experimentName 不能为空')
    }
    formData.append('experimentName', experimentName)

    const token = tokenStore.token
    if (!token) {
      throw new Error('Token 不能为空')
    }

    const response = await api.post('/transmission', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        token: tokenStore.token
      }
    })

    console.log('上传响应:', response.data)

    if (response.data.code === 200) {
      ElMessage.success('文件上传成功')
      // 确保 fileUrls 是一个字符串
      group.fileUrls = response.data.data?.url || ''
    } else {
      throw new Error(response.data.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(`文件上传失败，请重试: ${error.message}`)
    group.fileUrls = ''
    group._displayFolderName = ''
  } finally {
    // 隐藏加载动画
    if (loadingInstance) loadingInstance.close()
  }
}

//文件名预览

const handlePreview = (group) => {
  if (typeof group.fileUrls === 'string' && group.fileUrls.includes('/')) {
    // 假设文件夹名称是从地址中解析出来的
    const folderName = group.fileUrls.split('/').slice(-2, -1)[0] // 提取倒数第二级路径作为文件夹名称
    ElMessage.info(`文件夹名称: ${folderName}`)
  } else {
    ElMessage.error('无法预览文件夹名称')
  }
}

// 删除已选择的文件夹
const removeSelectedFolder = (group) => {
  // 清除预览 URL
  if (group.previewUrls) {
    group.previewUrls.forEach((url) => URL.revokeObjectURL(url))
    group.previewUrls = []
  }
  group.folderName = '' // 清除文件夹名称
  group.fileUrls = '' // 清除文件列表
  group._displayFolderName = ''
}

const experimentStore = useExperimentStore()
const { collectedExperiments } = experimentStore
// // 在组件挂载时加载存储的数据\

// 确保数据变化时页面自动更新
watchEffect(() => {
  experimentStore.collectedExperiments = collectedExperiments
})

// //当页面数据为空是，加载存储库中的数据
const collectData = async () => {
  const experimentStore = useExperimentStore() // 实例化 store
  experimentStore.reset()

  // 获取实验名称、团队名称
  const experimentDetectData = {
    experimentName: nameGroup.value.exper_name,
    teamName: nameGroup.value.teamName || '', // 添加默认空字符串
    experimentRounds: []
  }

  // 检查必要的字段是否存在
  if (!experimentDetectData.experimentName || !experimentDetectData.teamName) {
    ElMessage.warning('请填写实验名称和团队名称')
    return
  }

  // 收集实验轮次数据
  experimentDetectList.value.forEach((experiment) => {
    const rounds = experiment.experimentRounds || []
    rounds.forEach((round, roundIndex) => {
      if (!round.isSelected) return // **跳过未选中的实验轮次**

      const roundName = round.roundName || `第${roundIndex + 1}次实验`

      const timePoints = round.timePoints || []
      const timePointData = timePoints.map((timePoint, timePointIndex) => {
        // 添加时间格式转换
        let formattedTime = ''
        if (timePoint.timePointName) {
          const date = new Date(timePoint.timePointName)
          formattedTime = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
        }

        const groups = timePoint.groups || []
        const selectedGroups = groups
          .filter((group) => group.isSelected)
          .map((group) => ({
            groupName: group.name || `组${timePointIndex + 1}`,
            fileUrls: Array.isArray(group.fileUrls)
              ? group.fileUrls.map((file) =>
                  typeof file === 'string' ? file : file.url || ''
                )
              : typeof group.fileUrls === 'string'
                ? group.fileUrls
                : ''
          }))

        return {
          timePointName: formattedTime, // 使用转换后的时间格式
          groups: selectedGroups
        }
      })

      // **过滤掉没有组的时间点**
      const filteredTimePoints = timePointData.filter(
        (tp) => tp.groups.length > 0
      )

      if (filteredTimePoints.length > 0) {
        experimentDetectData.experimentRounds.push({
          roundName,
          timePoints: filteredTimePoints
        })
      }
    })
  })

  // **如果没有选中的实验轮次或组，给出提示**
  if (experimentDetectData.experimentRounds.length === 0) {
    ElMessage.warning('请选择至少一个实验轮次和组！')
    return
  }

  // 将收集的数据存储到 store 中
  experimentStore.collectExperiments(experimentDetectData)

  try {
    const response = await api.post('/detect', experimentDetectData, {
      headers: {
        'Content-Type': 'application/json',
        token: tokenStore.token
      }
    })

    console.log('响应数据:', response.data)

    //  使用 query 参数传递数据
    await router.push({
      path: '/result',
      query: { data: JSON.stringify(response.data) }
    })

    // 如果请求成功，显示成功消息
    ElMessage.success('请求成功，数据已获取')
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error(
      '请求失败：' +
        (error.response?.data?.message || error.message || '未知错误')
    )
  }
}

onMounted(async () => {
  // 获取团队列表
  await teamNameStore.fetchTeamList()

  // 保留原有的其他 onMounted 逻辑
  if (!nameGroup.value.exper_name) {
    nameGroup.value.exper_name =
      experimentStore.collectedExperiments.experimentName
  }

  if (!nameGroup.value.teamName) {
    nameGroup.value.teamName = teamNameStore.teamName
  }
  const storedData = localStorage.getItem('experimentDetectList')
  if (storedData) {
    experimentDetectList.value = JSON.parse(storedData)
  } else {
    // 初始化默认数据
    experimentDetectList.value = [
      {
        experimentName: '',
        experimentRounds: [
          {
            roundName: '第1次实验',
            timePoints: [
              {
                timePointName: '',
                groups: [
                  { name: '正常组', fileUrls: '' },
                  { name: '感染组', fileUrls: '' },
                  { name: '疫苗组', fileUrls: '' }
                ]
              }
            ]
          }
        ]
      }
    ]
  }

  // 确保在页面刷新时清除文件夹名称
  experimentDetectList.value.forEach((experiment) => {
    experiment.experimentRounds.forEach((round) => {
      round.timePoints.forEach((timePoint) => {
        timePoint.groups.forEach((group) => {
          removeSelectedFolder(group)
        })
      })
    })
  })
})
// 监听 experimentDetectList 的变化，并在变化时更新 localStorage
watch(
  experimentDetectList,
  (newValue) => {
    localStorage.setItem('experimentDetectList', JSON.stringify(newValue))
  },
  { deep: true } // 深度监听，以便监听到嵌套数据的变化
)

const rules = ref({
  name: [
    { required: true, message: '组名不能为空', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        // 确保当前实验、轮次和时间点的索引存在
        const experiment =
          experimentDetectList.value[currentExperimentIndex.value]
        const round = experiment?.experimentRounds?.[currentRoundIndex.value]
        const timePoint = round?.timePoints?.[currentTimePointIndex.value]

        // 如果 timePoint 不存在，直接返回验证通过（避免未定义错误）
        if (!timePoint) {
          callback()
          return
        }

        // 获取当前时间点下的所有组
        const groups = timePoint.groups

        // 排除当前组，提取其他组的名称
        const groupNames = groups
          .filter((g, idx) => idx !== currentGroupIndex.value)
          .map((g) => g.name)

        // 检查新组名是否已经存在
        if (groupNames.includes(value)) {
          callback(new Error('组名不能重复'))
        } else {
          callback() // 验证通过
        }
      },
      trigger: 'blur'
    }
  ],
  dateTime: [
    { required: true, message: '请选择时间', trigger: 'change' },
    {
      validator(rule, value, callback) {
        const now = new Date()
        if (value && new Date(value).getTime() > now.getTime()) {
          callback(new Error('选择的时间不能超过当前时间'))
        } else {
          callback() // 验证通过
        }
      },
      trigger: 'change'
    }
  ]
})

// 打开组编辑对话框
const openEditDialog = (
  experimentIndex,
  roundIndex,
  timePointIndex,
  groupIndex
) => {
  // 设置当前索引值
  currentExperimentIndex.value = experimentIndex
  currentRoundIndex.value = roundIndex
  currentTimePointIndex.value = timePointIndex
  currentGroupIndex.value = groupIndex

  // 设置当前组名称
  const group =
    experimentDetectList.value[experimentIndex]?.experimentRounds?.[roundIndex]
      ?.timePoints?.[timePointIndex]?.groups?.[groupIndex]
  if (group) {
    currentGroup.value.name = group.name
    editGroupDialogVisible.value = true
  } else {
    ElMessage.error('无法找到对应的组')
  }
}

// 表单验证并确认编辑
const confirmEditGroup = () => {
  nextTick(() => {
    if (!editGroupForm.value) {
      ElMessage.error('表单未初始化')
      return
    }

    editGroupForm.value.validate((valid) => {
      if (valid) {
        // 检查每个层级是否存在，避免空值错误
        const experiment =
          experimentDetectList.value[currentExperimentIndex.value]
        const round = experiment?.experimentRounds?.[currentRoundIndex.value]
        const timePoint = round?.timePoints?.[currentTimePointIndex.value]
        const group = timePoint?.groups?.[currentGroupIndex.value]

        if (!group) {
          ElMessage.error('无法找到对应的组')
          return
        }

        // 更新组名
        if (group.name !== currentGroup.value.name) {
          group.name = currentGroup.value.name
          editGroupDialogVisible.value = false
          ElMessage.success('组名已更新')
        } else {
          ElMessage.warning('组名未更改')
        }
      }
    })
  })
}

// 关闭对话框
const closeEditDialog = () => {
  editGroupDialogVisible.value = false
}

const handleRoundSelection = (experimentIndex, roundIndex) => {
  // 计算所有已选中的轮次数量
  const selectedRounds = experimentDetectList.value
    .flatMap((exp) => exp.experimentRounds)
    .filter((round) => round.isSelected)

  if (selectedRounds.length > 1) {
    ElMessage.error('只能选择一个实验轮次！')
    experimentDetectList.value[experimentIndex].experimentRounds[
      roundIndex
    ].isSelected = false
  }
}

//组选中状态的监听
const handleGroupSelection = (
  experimentIndex,
  roundIndex,
  timePointIndex,
  groupIndex
) => {
  let selectedGroup =
    experimentDetectList.value[experimentIndex].experimentRounds[roundIndex]
      .timePoints[timePointIndex].groups[groupIndex]

  // 获取当前已选中的组
  let selectedGroups = []
  let firstSelectedExperimentIndex = null
  let firstSelectedTimePointIndex = null

  // 遍历所有实验，查找已选中的组
  experimentDetectList.value.forEach((experiment, expIndex) => {
    experiment.experimentRounds.forEach((round) => {
      round.timePoints.forEach((tp, tpIndex) => {
        tp.groups.forEach((group) => {
          if (group.isSelected) {
            selectedGroups.push({
              experimentIndex: expIndex,
              timePointIndex: tpIndex
            })

            if (firstSelectedExperimentIndex === null) {
              firstSelectedExperimentIndex = expIndex
              firstSelectedTimePointIndex = tpIndex
            }
          }
        })
      })
    })
  })

  // 如果是变化趋势模式
  if (radios.value === 1) {
    // 获取当前组的名称
    const currentGroupName = selectedGroup.name

    // 获取所有时间点中相同名称的组
    const allTimePoints =
      experimentDetectList.value[experimentIndex].experimentRounds[roundIndex]
        .timePoints
    const sameNameGroups = allTimePoints
      .map((timePoint) =>
        timePoint.groups.find((g) => g.name === currentGroupName)
      )
      .filter(Boolean)

    // 检查是否所有时间点都有这个组
    if (sameNameGroups.length !== allTimePoints.length) {
      ElMessage.error('变化趋势模式下，必须选择所有时间点中相同名称的组！')
      selectedGroup.isSelected = false
      return
    }

    // 如果取消选中，同时取消所有相同名称的组
    if (!selectedGroup.isSelected) {
      allTimePoints.forEach((timePoint) => {
        const group = timePoint.groups.find((g) => g.name === currentGroupName)
        if (group) {
          group.isSelected = false
        }
      })
    } else {
      // 如果选中，同时选中所有相同名称的组
      allTimePoints.forEach((timePoint) => {
        const group = timePoint.groups.find((g) => g.name === currentGroupName)
        if (group) {
          group.isSelected = true
        }
      })
    }
  }
  // 同时间对比模式的逻辑保持不变
  else if (radios.value === 2) {
    if (
      selectedGroups.length > 0 &&
      (firstSelectedExperimentIndex !== experimentIndex ||
        firstSelectedTimePointIndex !== timePointIndex)
    ) {
      ElMessage.error(
        '同时间对比模式下，只能选择同一次实验的同一个时间点的组！'
      )
      selectedGroup.isSelected = false
      return
    }
  }
}
const openAddGroupDialog = (experimentIndex, roundIndex, timePointIndex) => {
  currentExperimentIndex.value = experimentIndex
  currentRoundIndex.value = roundIndex
  currentTimePointIndex.value = timePointIndex
  newGroupName.value = ''
  addGroupDialogVisible.value = true
}

// 确认添加组
const confirmAddGroup = () => {
  if (!newGroupName.value) {
    ElMessage.error('组名不能为空')
    return
  }

  // 获取当前实验、轮次和时间点的索引，并找到当前时间点的所有组
  const experiment = experimentDetectList.value[currentExperimentIndex.value]
  const round = experiment?.experimentRounds?.[currentRoundIndex.value]
  const timePoint = round?.timePoints?.[currentTimePointIndex.value]

  // 如果 timePoint 不存在，显示错误消息并返回
  if (!timePoint) {
    ElMessage.error('无法找到对应的时间点')
    return
  }

  // 获取当前时间点下的所有组名
  const existingGroupNames = timePoint.groups.map((g) => g.name)

  // 检查新组名是否已经存在
  if (existingGroupNames.includes(newGroupName.value)) {
    ElMessage.error('组名不能重复')
    return
  }

  // 如果组名唯一，则添加组
  timePoint.groups.push({
    name: newGroupName.value,
    fileUrls: ''
  })

  addGroupDialogVisible.value = false
}

const closeAddGroupDialog = () => {
  addGroupDialogVisible.value = false
}
// 删除组
const removeGroup = (
  experimentIndex,
  roundIndex,
  timePointIndex,
  groupIndex
) => {
  showConfirmDialog('删除确认', '确定要删除此组吗？', () => {
    experimentDetectList.value[experimentIndex].experimentRounds[
      roundIndex
    ].timePoints[timePointIndex].groups.splice(groupIndex, 1)
  })
}

// 删除最新实验
const removeLatestExperiment = () => {
  if (experimentDetectList.value.length === 0) {
    ElMessage.warning('没有更多实验可以删除')
    return
  }

  // 显示确认框
  ElMessageBox.confirm('确定要删除最新的实验吗？', '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 用户确认删除
      experimentDetectList.value.pop()

      // 显示删除成功的提示消息
      ElMessage({
        type: 'success',
        message: '最新实验已删除'
      })
    })
    .catch(() => {
      // 用户取消删除
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

const addTimePoint = (experimentIndex, roundIndex) => {
  experimentDetectList.value[experimentIndex].experimentRounds[
    roundIndex
  ].timePoints.push({
    timePointName: '', // 新的时间点
    groups: [
      { name: '正常组', fileUrls: '', isSelected: false },
      { name: '感染组', fileUrls: '', isSelected: false },
      { name: '疫苗组', fileUrls: '', isSelected: false }
    ]
  })
}

// 删除时间点
const removeTimePoint = (experimentIndex, roundIndex, timePointIndex) => {
  // 显示确认框
  ElMessageBox.confirm('确定要删除此时间点吗？', '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 用户确认删除
      experimentDetectList.value[experimentIndex].experimentRounds[
        roundIndex
      ].timePoints.splice(timePointIndex, 1)

      // 显示删除成功的提示消息
      ElMessage({
        type: 'success',
        message: '时间点已删除'
      })
    })
    .catch(() => {
      // 用户取消删除
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

const addExperiment = () => {
  experimentDetectList.value.push({
    experimentName: '',
    experimentRounds: [
      {
        roundName: `第 ${experimentDetectList.value.length + 1} 次实验`, // 动态显示实验轮次名称
        isSelected: false, // 可以添加默认是否选中的状态
        timePoints: [
          {
            timePointName: '', // 默认时间点名称为空
            groups: [
              { name: '正常组', fileUrls: '', isSelected: false },
              { name: '感染组', fileUrls: '', isSelected: false },
              { name: '疫苗组', fileUrls: '', isSelected: false }
            ]
          }
        ]
      }
    ]
  })
}

// 表单失去焦点事件
const handleBlur = () => {
  if (!currentGroup.value.name) {
    errorMessage.value = '组名不能为空'
  } else {
    errorMessage.value = ''
  }
}
// 监听，当弹出框关闭时，重置表单数据
watch(dialogFormVisible, (newValue) => {
  if (!newValue) {
    // 清除验证的消息
    errorMessage.value = ''
  }
})

// 监听模态框的关闭
watch(dialogFormVisible, (newValue) => {
  if (!newValue) {
    errorMessage.value = '' // 清空验证消息
  }
})

//js中间部分结束
//js头部开始

const confirmNewExperiment = async () => {
  if (
    !newExperimentData.value.experimentName ||
    !newExperimentData.value.teamName
  ) {
    ElMessage.error('实验名称和团队名称不能为空')
    return
  }

  try {
    const response = await api.post(
      '/new',
      {
        experimentName: newExperimentData.value.experimentName,
        teamName: newExperimentData.value.teamName
      },
      {
        headers: {
          'Content-Type': 'application/json',
          token: tokenStore.token
        }
      }
    )

    if (response.status === 200) {
      ElMessage.success('实验创建成功')
      dialogNewExp.value = false
      // 清空输入字段
      newExperimentData.value.experimentName = ''
      newExperimentData.value.teamName = ''
      experimentDetectList.value = [
        {
          experimentName: '',
          experimentRounds: [
            {
              roundName: '第1次实验',
              timePoints: [
                {
                  timePointName: '',
                  groups: [
                    { name: '正常组', fileUrls: '', isSelected: false },
                    { name: '感染组', fileUrls: '', isSelected: false },
                    { name: '疫苗组', fileUrls: '', isSelected: false }
                  ]
                }
              ]
            }
          ]
        }
      ]
    } else {
      ElMessage.error('实验创建失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('请求失败，请重试')
  }
}
const route = useRoute()
onMounted(() => {
  if (route.query && route.query.trigger === 'result') {
    confirmNewExperiment()
  }
  router.replace({ path: '/ceter', query: {} })
})

// 添加图片预览对话框相关变量
const previewDialogVisible = ref(false)
const previewImages = ref([])

// 添加图片预览函数
const showImagePreview = (group) => {
  if (group.previewUrls && group.previewUrls.length > 0) {
    previewImages.value = group.previewUrls
    previewDialogVisible.value = true
  } else {
    ElMessage.warning('没有可预览的图片')
  }
}

// 提取公共的确认对话框逻辑
const showConfirmDialog = (title, message, onConfirm) => {
  return ElMessageBox.confirm(message, title, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      onConfirm()
      ElMessage.success('操作成功')
    })
    .catch(() => {
      ElMessage.info('已取消操作')
    })
}
</script>
<template>
  <div class="common-layout">
    <el-container>
      <el-container>
        <CommonHeader />
        <el-main>
          <!-- 遍历实验列表 -->
          <div
            v-for="(experiment, experimentIndex) in experimentDetectList"
            :key="experimentIndex"
          >
            <div
              v-for="(round, roundIndex) in experiment.experimentRounds"
              :key="roundIndex"
            >
              <h3>{{ round.roundName }}</h3>
              <el-checkbox
                v-model="round.isSelected"
                @change="handleRoundSelection(experimentIndex, roundIndex)"
              >
                选择
              </el-checkbox>

              <el-collapse v-model="activeNames" accordion>
                <!-- 遍历每个时间点 -->
                <el-collapse-item
                  v-for="(timePoint, timePointIndex) in round.timePoints"
                  :key="timePointIndex"
                  :name="`${experimentIndex}-${roundIndex}-${timePointIndex}`"
                >
                  <!-- 时间点的标题 -->
                  <template #title>
                    <el-date-picker
                      v-model="timePoint.timePointName"
                      type="datetime"
                      placeholder="选择时间"
                      :disabled-hours="disabledHours"
                      :disabled-minutes="disabledMinutes"
                      :disabled-seconds="disabledSeconds"
                      :disabled-date="disabledDate"
                    ></el-date-picker>
                  </template>

                  <!-- 时间点内容 -->
                  <el-card>
                    <el-form>
                      <!-- 组列表 -->
                      <div
                        v-for="(group, groupIndex) in timePoint.groups"
                        :key="groupIndex"
                      >
                        <div>
                          <!-- 文件选择按钮 -->
                          <el-row :gutter="20">
                            <el-col :span="9">{{ group.name }}</el-col>
                            <el-col :span="4">
                              <!-- el-upload 组件用于展示文件列表 -->
                              <el-upload
                                :file-list="[]"
                                :on-preview="handlePreview"
                                list-type="text"
                                :before-upload="() => false"
                              >
                                <el-button
                                  type="primary"
                                  @click.stop="
                                    () =>
                                      triggerDirectoryInput(
                                        experimentIndex,
                                        roundIndex,
                                        timePointIndex,
                                        groupIndex
                                      )
                                  "
                                >
                                  选择文件夹
                                </el-button>
                              </el-upload>

                              <!-- 添加预览按钮 -->
                              <el-button
                                v-if="
                                  group.previewUrls &&
                                  group.previewUrls.length > 0
                                "
                                type="primary"
                                @click="() => showImagePreview(group)"
                              >
                                预览图片
                              </el-button>

                              <!-- 显示文件夹名称 -->
                              <div
                                v-if="group._displayFolderName"
                                class="folder-name"
                                style="font-size: 20px"
                              >
                                {{ group._displayFolderName }}
                                <el-icon
                                  style="position: absolute"
                                  @click="removeSelectedFolder(group)"
                                >
                                  <Close />
                                </el-icon>
                              </div>

                              <!-- 隐藏的文件夹选择 input -->
                              <input
                                type="file"
                                style="display: none"
                                webkitdirectory
                                :ref="
                                  (el) =>
                                    setDirectoryInputRef(
                                      el,
                                      experimentIndex,
                                      roundIndex,
                                      timePointIndex,
                                      groupIndex
                                    )
                                "
                                @change="
                                  (e) =>
                                    handleDirectoryChange(
                                      e,
                                      group,
                                      experimentIndex,
                                      roundIndex,
                                      timePointIndex
                                    )
                                "
                              />
                            </el-col>
                            <el-col :span="3">
                              <el-checkbox
                                v-model="group.isSelected"
                                @change="
                                  handleGroupSelection(
                                    experimentIndex,
                                    roundIndex,
                                    timePointIndex,
                                    groupIndex
                                  )
                                "
                              >
                                选择本组
                              </el-checkbox>
                            </el-col>

                            <el-col :span="7">
                              <el-button
                                plain
                                @click="
                                  openEditDialog(
                                    experimentIndex,
                                    roundIndex,
                                    timePointIndex,
                                    groupIndex
                                  )
                                "
                              >
                                编辑
                              </el-button>
                              <el-button
                                type="danger"
                                @click="
                                  removeGroup(
                                    experimentIndex,
                                    roundIndex,
                                    timePointIndex,
                                    groupIndex
                                  )
                                "
                              >
                                删除
                              </el-button>
                            </el-col>
                          </el-row>
                        </div>
                      </div>

                      <!-- 添加组按钮 -->
                      <el-button
                        @click="
                          openAddGroupDialog(
                            experimentIndex,
                            roundIndex,
                            timePointIndex
                          )
                        "
                        type="primary"
                      >
                        添加组
                      </el-button>

                      <!-- 删除时间点按钮 -->
                      <el-button
                        @click="
                          removeTimePoint(
                            experimentIndex,
                            roundIndex,
                            timePointIndex
                          )
                        "
                        type="danger"
                      >
                        删除时间点
                      </el-button>
                    </el-form>
                  </el-card>
                </el-collapse-item>
              </el-collapse>

              <!-- 添加时间点按钮 -->
              <el-button
                @click="addTimePoint(experimentIndex, roundIndex)"
                class="bottom-button"
              >
                添加时间点
              </el-button>
            </div>
          </div>

          <!-- 添加实验按钮 -->
          <div>
            <el-row :gutter="20">
              <el-col :span="20">
                <el-button @click="addExperiment" class="bottom-button">
                  添加实验
                </el-button>
              </el-col>
              <el-col :span="4">
                <el-button
                  @click="removeLatestExperiment"
                  class="bottom-button"
                >
                  删除实验
                </el-button>
              </el-col>
            </el-row>
          </div>
        </el-main>
        <el-footer>
          <div class="bottom">
            <div class="box">
              <el-row :gutter="20" class="all">
                <el-col :span="7">
                  <el-container>
                    <el-aside style="width: 230px; margin-left: 10px">
                      实验名称:
                      <el-input
                        style="width: 140px; margin: 20px 5px"
                        placeholder="请输入实验名称"
                        v-model="
                          experimentStore.collectedExperiments.experimentName
                        "
                      />
                      <br />
                      <span>选择团队:</span>
                      <el-select
                        v-model="teamNameStore.teamName"
                        placeholder="请选择团队"
                        style="width: 145px; margin: 20px 5px"
                      >
                        <el-option
                          v-for="item in teamNameStore.teamOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-aside>
                  </el-container>
                </el-col>
                <el-col :span="2"> </el-col>
                <el-col :span="2">
                  <el-aside style="margin: 20px 0px">测试方法:</el-aside>
                </el-col>
                <el-col :span="3">
                  <el-aside style="margin: 20px 20px">
                    <el-radio-group
                      v-model="radios"
                      type="vertical"
                      style="
                        display: flex;
                        flex-flow: column nowrap;
                        align-items: flex-start;
                      "
                    >
                      <el-radio :value="1">变化趋势</el-radio>
                      <el-radio :value="2">同时间对比</el-radio>
                    </el-radio-group>
                  </el-aside>
                </el-col>
                <el-col :span="3" class="vertical-center"></el-col>
                <el-col :span="6" class="vertical-center">
                  <el-button
                    round
                    size="large"
                    style="background-color: #ccf783; color: #101010"
                    @click="collectData"
                    :disabled="!isFolderUploaded"
                  >
                    检测
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </div>

  <!-- 添加图片预览对话框 -->
  <el-dialog v-model="previewDialogVisible" title="图片预览" width="80%">
    <el-carousel height="400px">
      <el-carousel-item v-for="(url, index) in previewImages" :key="index">
        <img
          :src="url"
          style="max-width: 100%; max-height: 100%; object-fit: contain"
        />
      </el-carousel-item>
    </el-carousel>
  </el-dialog>

  <!-- 组编辑对话框 -->
  <el-dialog v-model="editGroupDialogVisible" title="编辑组">
    <el-form ref="editGroupForm" :model="currentGroup" :rules="rules">
      <!-- 添加提示信息 -->
      <el-alert
        title="请保持每个小组名称的一致性"
        type="warning"
        show-icon
        style="margin-bottom: 10px"
      />

      <el-form-item label="组名" :label-width="formLabelWidth" prop="name">
        <el-input v-model="currentGroup.name" @blur="handleBlur"></el-input>
      </el-form-item>

      <el-form-item>
        <span class="error-message" v-if="errorMessage">{{
          errorMessage
        }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="confirmEditGroup">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 组添加对话框 -->
  <el-dialog v-model="addGroupDialogVisible" title="添加组">
    <el-form>
      <el-form-item label="组名" :label-width="formLabelWidth">
        <el-input v-model="newGroupName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeAddGroupDialog">取消</el-button>
        <el-button type="primary" @click="confirmAddGroup">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.el-main {
  --el-main-padding: 20px;
  background-color: #f8f8fb;
  min-height: calc(100vh - 160px);
  padding: 32px;
}

.el-header {
  --el-header-padding: 0;
  background: #ffffff;
  box-shadow: 0 2px 4px rgba(115, 103, 240, 0.1);
}

.el-footer {
  --el-footer-padding: 0;
  background: #ffffff;
  box-shadow: 0 -2px 4px rgba(115, 103, 240, 0.1);
  padding: 24px;
}

.banner {
  padding: 32px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
  margin-bottom: 24px;

  .container {
    max-width: 1200px;
    margin: 0 auto;
  }
}

h3 {
  background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
  color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  margin: 24px 0 16px;
  font-size: 18px;
  font-weight: 500;
  box-shadow: 0 4px 16px rgba(115, 103, 240, 0.15);
}

.el-collapse {
  border: none;
  margin-bottom: 16px;

  .el-collapse-item {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 16px;
    box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
    overflow: hidden;

    &__header {
      padding: 20px;
      font-weight: 500;
      color: #1e1e2d;
      background: linear-gradient(to right, #f8f8fb, #ffffff);
      border-bottom: 1px solid rgba(115, 103, 240, 0.1);
    }

    &__content {
      padding: 24px;
    }
  }
}

.el-card {
  border: none;
  border-radius: 16px;
  margin-bottom: 24px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 32px rgba(115, 103, 240, 0.12);
  }

  .el-card__header {
    padding: 20px 24px;
    border-bottom: 1px solid rgba(115, 103, 240, 0.1);
    background: linear-gradient(to right, #f8f8fb, #ffffff);
  }

  .el-card__body {
    padding: 24px;
  }
}

.el-button {
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;

  &--primary {
    background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
    border: none;
    color: #ffffff;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(115, 103, 240, 0.3);
    }
  }

  &--danger {
    background: #ffffff;
    border: 1px solid #ff4d4f;
    color: #ff4d4f;

    &:hover {
      background: #ff4d4f;
      color: #ffffff;
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(255, 77, 79, 0.3);
    }
  }
}

.bottom {
  padding: 24px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);

  .box {
    max-width: 1200px;
    margin: 0 auto;

    .all {
      background: linear-gradient(to right, #f8f8fb, #ffffff);
      padding: 24px;
      border-radius: 16px;
      box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
    }
  }
}

.el-select,
.el-input {
  :deep(.el-input__wrapper) {
    box-shadow: 0 2px 12px rgba(115, 103, 240, 0.1);
    border-radius: 8px;
    padding: 0 16px;

    &:hover {
      box-shadow: 0 4px 16px rgba(115, 103, 240, 0.15);
    }

    &.is-focus {
      box-shadow: 0 0 0 2px rgba(115, 103, 240, 0.2);
    }
  }
}

.el-checkbox {
  margin-right: 16px;

  :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #7367f0;
    border-color: #7367f0;
  }

  :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
    color: #7367f0;
  }
}

.el-radio-group {
  .el-radio {
    margin-bottom: 12px;

    :deep(.el-radio__input.is-checked .el-radio__inner) {
      background-color: #7367f0;
      border-color: #7367f0;
    }

    :deep(.el-radio__input.is-checked + .el-radio__label) {
      color: #7367f0;
    }
  }
}

.folder-name {
  background: #f8f8fb;
  padding: 12px 16px;
  border-radius: 8px;
  margin-top: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid rgba(115, 103, 240, 0.1);

  .el-icon {
    cursor: pointer;
    color: #6e6b7b;
    transition: all 0.3s ease;

    &:hover {
      color: #ff4d4f;
      transform: scale(1.1);
    }
  }
}
</style>
